package com.ruoyi.framework.web.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysDeptEnterprise;
import com.ruoyi.common.core.domain.entity.SysEnterprise;
import com.ruoyi.common.core.domain.entity.SysUserEnterprise;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysStaff;
import com.ruoyi.system.domain.SysStaffDeptEnterpriseRel;
import com.ruoyi.system.domain.vo.QyWxMessage;
import com.ruoyi.system.mapper.SysEnterpriseMapper;
import com.ruoyi.system.service.ISysDeptEnterpriseService;
import com.ruoyi.system.service.ISysStaffDeptEnterpriseRelService;
import com.ruoyi.system.service.ISysStaffService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * 企业微信消息推送服务
 *
 * @author LANIAKEA
 * @since 2025/3/3 14:43
 */
@Component
@Slf4j
public class QywxMessageService {
    @Resource
    private SysEnterpriseMapper sysEnterpriseMapper;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysStaffService sysStaffService;

    public String sendMarkDownMsg(String staffId, String content) {

        log.info("登录用户：{}，对staffId:{}发送了企业微信消息，内容为：{}"
                , SecurityUtils.getLoginUser().getUserId(), staffId, content);
        content = content.replaceAll("####", "<").replaceAll("@@@@", ">");
        String result = "";
        SysStaff staff = this.sysStaffService.selectSysStaffByStaffId(Long.valueOf(staffId));
        if (ObjectUtil.isEmpty(staff)) {
            result = "发送失败，用户;【" + staffId + "】不存在";
            log.info(result);
            return result;
        }
        if (StrUtil.isBlankIfStr(staff.getEnterpriseUserId())) {
            result = "发送失败，用户;【" + staffId + "】不存在企业微信ID";
            log.info(result);
            return result;
        }
        QyWxMessage qyWxMessage = new QyWxMessage();
        qyWxMessage.setTouser(staff.getEnterpriseUserId());
        qyWxMessage.setToparty("");
        qyWxMessage.setTotag("");
        qyWxMessage.setMsgtype("markdown");
        qyWxMessage.setAgentid(1000002);
        qyWxMessage.setMarkdown(new QyWxMessage.Markdown(content));
        qyWxMessage.setEnable_duplicate_check(0);
        qyWxMessage.setDuplicate_check_interval(180);
        result = this.sendMarkDownMsg(qyWxMessage);
        log.info("发送结果:{}", result);
        return result;


    }


    /**
     * 发送markdown消息
     *
     * @param qyWxMessage
     */
    public String sendMarkDownMsg(QyWxMessage qyWxMessage) {
        //String corpId = getLoginUserCorpId();
        String corpId = "wwd7a63ec9e4e28872";


        SysEnterprise sysEnterprise = sysEnterpriseMapper.selectSysEnterpriseByCorpid(corpId);
        String accessToken = loginService.getEnterpriseAccessToken(corpId, sysEnterprise.getCorpsecret());
        String url = StringUtils.format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}", accessToken);

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(qyWxMessage));

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//忽略多余字段
            JsonNode rootNode = objectMapper.readTree(result);
            int errcode = rootNode.get("errcode").asInt();
            if (errcode == 0) {
                return "发送成功";
            } else {
                return rootNode.get("errmsg").asText();
            }
        } catch (Exception e) {
            log.error("发送企业微信markdown消息出错了", e);
            return "发送出错了";
        }
    }

    private String getLoginUserCorpId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserEnterprise userEnterprise = loginUser.getUserEnterprise();
        if (userEnterprise == null) {
            throw new ServiceException("未获取到当前登录用户的企业微信信息");
        }
        return userEnterprise.getEnterpriseCorpId();
    }


}

